import React, { memo, useMemo } from 'react'

import { Form, Input, InputNumber, Button } from 'antd'

import { BwUpload } from '@/components/common'

import '@/assets/less/product/productSpecTable.less'
const { List, Item } = Form

export default memo(function (props) {
  /**
   * 统一配置操作列表头
   */
  const modifyWorkColumn = useMemo(
    () => ({
      title: '操作',
      dataIndex: 'operate',
      render: index => (
        <>
          <Button type="text" onClick={() => props.updateSpecList('modify')}>
            批量修改
          </Button>
          |
          <Button type="text" onClick={() => props.updateSpecList('clean')}>
            清空
          </Button>
        </>
      ),
    }),
    [props]
  )

  /**
   * sku操作列表头
   */
  const workColumn = useMemo(
    () => ({
      title: '操作',
      dataIndex: 'operate',
      render: index => (
        <Button type="text" onClick={() => props.updateSpecList('delete', index)}>
          删除
        </Button>
      ),
    }),
    [props]
  )

  /**
   * 完整表头获取
   */
  const columns = useMemo(() => {
    let columns = [...defaultColumns]
    if (props.updateSpecList) {
      columns = [...defaultColumns, modifyWorkColumn]
    }
    if (props.skuColumns && props.skuColumns.length) {
      columns = [...props.skuColumns, ...defaultColumns, workColumn]
    }
    return columns
  }, [props, workColumn, modifyWorkColumn])

  /**
   * 渲染表头
   * @returns
   */
  function renderHeader() {
    return [...columns].map(item => (
      <th key={item.dataIndex} className={item.type}>
        {item.title}
      </th>
    ))
  }

  /**
   * 渲染行
   * @param {*} data
   * @param {*} index
   * @param {*} list
   * @returns
   */
  function renderAttrs(data, index, list) {
    const attrs = [...columns].map(item => (
      <td key={`${item.dataIndex}_${index}`} className={item.type}>
        {item.render(index)}
      </td>
    ))
    return <tr key={index}>{attrs}</tr>
  }

  return (
    <table className="product-spec-table">
      <thead>
        <tr>{renderHeader()}</tr>
      </thead>
      <tbody>
          <List name="attrs">{fileds => fileds.map(renderAttrs)}</List>
      </tbody>
    </table>
  )
})
